package net.chengp.ms.auth.config;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import lombok.AllArgsConstructor;
import net.chengp.ms.auth.exception.AuthExceptionEntryPoint;
import net.chengp.ms.auth.exception.CustomWebResponseExceptionTranslator;
import net.chengp.ms.auth.filter.CustomClientCredentialsTokenEndpointFilter;
import net.chengp.ms.auth.service.UserDetailsServiceImpl;

/**
 * 认证服务器配置
 * 
 * @author chengp
 *
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

	private final JwtTokenEnhancer jwtTokenEnhancer;
	private final PasswordEncoder passwordEncoder;
	private final UserDetailsServiceImpl userDetailsService;
	private final AuthenticationManager authenticationManager;

	@Autowired
	private CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;

	@Autowired
	private JwtTokenJksConfig jwtTokenJksConfig;

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		// TODO 这里需要从数据库读取客户端信息
		clients.inMemory().withClient("client-app").redirectUris("http://www.baidu.com")
				.secret(passwordEncoder.encode("123456")).scopes("all").authorizedGrantTypes("client_credentials",
						"password", "refresh_token", "authorization_code", "implicit")
				.accessTokenValiditySeconds(3600).refreshTokenValiditySeconds(86400);
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
		List<TokenEnhancer> delegates = new ArrayList<>();
		delegates.add(jwtTokenEnhancer);
		delegates.add(accessTokenConverter());
		enhancerChain.setTokenEnhancers(delegates); // 配置JWT的内容增强器
		endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService) // 配置加载用户信息的服务
				.accessTokenConverter(accessTokenConverter()).tokenEnhancer(enhancerChain)
				.exceptionTranslator(customWebResponseExceptionTranslator).reuseRefreshTokens(true)
				.tokenStore(new JwtTokenStoreEnhance(accessTokenConverter()));
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(
				security);
		endpointFilter.afterPropertiesSet();
		endpointFilter.setAuthenticationEntryPoint(new AuthExceptionEntryPoint());
		security.addTokenEndpointAuthenticationFilter(endpointFilter);
		security.authenticationEntryPoint(new AuthExceptionEntryPoint()).tokenKeyAccess("isAuthenticated()")
				.checkTokenAccess("permitAll()");

	}

	@Bean
	public JwtAccessTokenConverter accessTokenConverter() {
		JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
		jwtAccessTokenConverter.setKeyPair(keyPair());
		return jwtAccessTokenConverter;
	}

	@Bean
	public KeyPair keyPair() {
		KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
				new ClassPathResource(jwtTokenJksConfig.getPath()), jwtTokenJksConfig.getPwd().toCharArray());
		return keyStoreKeyFactory.getKeyPair(jwtTokenJksConfig.getKeyAlias(),
				jwtTokenJksConfig.getKeyPwd().toCharArray());
	}

}
